import asyncio
from threading import Thread,currentThread,main_thread
import threading
import os

def sample_001():
    # 获取当前的事件循环
    loop = asyncio.get_event_loop()
    print(loop,id(loop))  #<ProactorEventLoop running=False closed=False debug=False>

    # 获取正在运行的事件循环
    try:
        #no running event loop
        print(asyncio.get_running_loop())
    except RuntimeError as e:
        print(e)


    loop2 = asyncio.new_event_loop()
    asyncio.set_event_loop(loop2)
    print(loop2,id(loop2))

def sample_002():
    class MyThread(Thread):
        """
        线程里直接 asyncio.get_event_loop  会抛出异常,asyncio.get_event_loop 只在主线程上创建了循环
        """
        def run(self):
            try:
                print(os.getpid())
                loop = asyncio.get_event_loop()
                #There is no current event loop in thread 'Thread-1'.

                print(f"in thread({os.getpid()})->",loop)
            except RuntimeError as e:
                print(e)

    loop = asyncio.get_event_loop()
    print(f"main({os.getpid()}) thread {currentThread().ident}->",loop)
    thread = MyThread()
    thread.start()
    thread.join()

if __name__ == '__main__':
    sample_002()